/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.bs.dao;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaQuery;
import org.apache.log4j.Logger;

/**
 *
 * @author gbran
 * @param <Entity>
 * @param <PrimaryKey>
 */
public abstract class AbstractFacade<Entity, PrimaryKey> {

    private final Class<Entity> clazz;
    protected static final Logger LOGGER = Logger.getLogger(AbstractFacade.class);

    public AbstractFacade(Class<Entity> clazz) {
        this.clazz = clazz;
    }

    public void save(Entity entity) {
        getEntityManager().persist(entity);
    }

    public void update(Entity entity) {
        getEntityManager().merge(entity);
    }

    public void delete(Entity entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public void refresh(Entity entity) {
        getEntityManager().refresh(entity);
    }

    public void clear() {
        getEntityManager().clear();
    }

    public void flush() {
        getEntityManager().flush();
    }

    public Entity find(PrimaryKey primaryKey) {
        return getEntityManager().find(clazz, primaryKey);
    }

    public List<Entity> findAll() {
        CriteriaQuery<Entity> criteriaQuery = getEntityManager().getCriteriaBuilder().createQuery(clazz);
        List<Entity> l = getEntityManager().createQuery(criteriaQuery).getResultList();
        return l != null ? l : new ArrayList<Entity>();
    }

    protected abstract EntityManager getEntityManager();
}
